#!/bin/bash

folder=$1   #fuzzer result folder
pno=$2      #port number
step=$3     #step to skip running gcovr and outputting data to covfile
            #e.g., step=5 means we run gcovr after every 5 test cases
covfile=$4  #path to coverage file
ssldir=$5
starttime=$6
endtime=$7
#delete the existing coverage file
rm $covfile; touch $covfile

#clear gcov data
gcovr -r $ssldir -s -d > /dev/null 2>&1

#output the header of the coverage file which is in the CSV format
#Time: timestamp, l_per/b_per and l_abs/b_abs: line/branch coverage in percentage and absolutate number
#echo "Time l_per l_abs b_per b_abs" >> $covfile

#files stored in replayable-* folders are structured
#in such a way that messages are separated
testdir="Seed"
replayer="/home/pany/profuzzbench/aflnet/aflnet-replay"

#process testcases
count=0
delta=0
for f in $(echo $folder/$testdir/*); do 
  time=$(stat -c %Y $f)
  echo $f
  if [ "$count" == "0" ]; then delta=$time; fi
  time=$(expr $time - $delta + $starttime)  
  if [ "$time" -gt "$endtime" ]; then break; fi
  $replayer $f TLS $pno 100 > /dev/null 2>&1 &
  # ./apps/openssl
  LD_PRELOAD=/home/pany/test/libgcov_preload.so timeout -k 0 3s $ssldir/apps/openssl s_server -key server.key -cert server.crt -CAfile cacert.pem -accept $pno > /dev/null 2>&1
  #LD_PRELOAD=/home/pany/test/libgcov_preload.so timeout -k 0 3s $ssldir/apps/openssl/openssl s_server -key server.key -cert server.crt -CAfile cacert.pem -accept $pno -HTTP > /dev/null 2>&1
  #LD_PRELOAD=/home/pany/test/libgcov_preload.so timeout -k 0 3s $ssldir/build/tool/bssl s_server -key server.key -accept 4443 -loop -cert server.crt > /dev/null 2>&1
  
  wait
  count=$(expr $count + 1)
  rem=$(expr $count % $step)
  if [ "$rem" != "0" ]; then continue; fi
  cov_data=$(gcovr -r $ssldir -s | grep "[lb][a-z]*:")
  l_per=$(echo "$cov_data" | grep lines | cut -d" " -f2 | rev | cut -c2- | rev)
  l_abs=$(echo "$cov_data" | grep lines | cut -d" " -f3 | cut -c2-)
  b_per=$(echo "$cov_data" | grep branch | cut -d" " -f2 | rev | cut -c2- | rev)
  b_abs=$(echo "$cov_data" | grep branch | cut -d" " -f3 | cut -c2-)
  
  echo "$time $l_per $l_abs $b_per $b_abs" >> $covfile
done

#ouput cov data for the last testcase(s) if step > 1
if [[ $step -gt 1 ]]
then
  time=$(stat -c %Y $f)
  time=$(expr $time - $delta + $starttime)
  if [ "$time" -le "$endtime" ]
  then
	  cov_data=$(gcovr -r $ssldir -s | grep "[lb][a-z]*:")
	  l_per=$(echo "$cov_data" | grep lines | cut -d" " -f2 | rev | cut -c2- | rev)
	  l_abs=$(echo "$cov_data" | grep lines | cut -d" " -f3 | cut -c2-)
	  b_per=$(echo "$cov_data" | grep branch | cut -d" " -f2 | rev | cut -c2- | rev)
	  b_abs=$(echo "$cov_data" | grep branch | cut -d" " -f3 | cut -c2-)
	  
	  echo "$time $l_per $l_abs $b_per $b_abs" >> $covfile
  fi
fi
